<template>
    <div class="customer">
        <div>
            <el-row>
                <el-col :span="24">
                    <el-button
                            type="primary"
                            @click="fanhui()">返回
                    </el-button>
                    <span style="font-size: 15px;margin-left: 10px;">新增/编辑商品</span>
                </el-col>
            </el-row>
            <div>
               <el-form :model="form"
                     style="background-color: #FFFFFF;padding-top:10px;height: 100%;margin-top: 10px;padding-left: 10px;"
                     label-width="150px" label-position='left'  ref="form">
                <el-form-item label="商品类型：">
                        <span>普通商品</span>
                </el-form-item>
                 <el-form-item label="商品分类：" v-if="showSort">
                    <el-select v-model="form.classifyCode" style="width: 200px;" @change="selectSort()"
                               placeholder="一级分类">
                        <el-option :label="item.classifyName" :value="item.classifyName"
                                   v-for="item in sortList"></el-option>
                    </el-select>
                    <el-select v-model="form.secondCode" style="width: 200px;" placeholder="二级分类" @change="selectSort2()">
                        <el-option :label="item.classifyName" :value="item.classifyName"
                                   v-for="item in secondList"></el-option>
                    </el-select>
                     <el-select v-model="form.thcondCode" style="width: 200px;" placeholder="三级分类">
                        <el-option :label="item.classifyName" :value="item.classifyName"
                                   v-for="item in thirdList"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称：">
                    <el-input style="width: 405px;" v-model="form.goodsName" :maxlength="50" ></el-input>
                </el-form-item>
                <el-form-item label="商品原价（元）：">
                    <el-input style="width: 200px;" v-model="form.price" :maxlength="8"></el-input>
                </el-form-item>
                <el-form-item label="商品现价（元）：">
                    <el-input style="width: 200px;" v-model="form.disPrice" :maxlength="8"></el-input>
                </el-form-item>
                <el-form-item label="商品重量（g）：" >
                    <el-input style="width: 200px;" v-model="form.weight" :maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="奖励积分比例：">
                    <el-select v-model="form.ratio" style="width: 200px;margin-right: 30px;">
                        <el-option :label="item.text" :value="item.value" v-for="item in proportion"></el-option>
                    </el-select>
                    <span>
              奖励积分：{{Math.round(form.disPrice*(form.ratio))}}
                </span>
                    </el-form-item>
                    <hr>
                    <el-form-item label="商品规格：">
                        <el-select v-model="sku_spec" style="width: 200px;" @change="select()">
                            <el-option :value="item" :label="item.standardName" v-for="item in sku_spec_array"></el-option>
                        </el-select>
                        <button class="btn btn-primary"@click.prevent="addSize()">前往新增规格</button>
                    </el-form-item>
                    <div style="clear: both;padding-top: 15px;"></div>
                    <div class="form-group" v-for="(item, index) in option_array" style="clear: both;" @change="generate">
                        <label class="col-sm-1 control-label input-none">{{item.sku_option_name}}：</label>
                        <div>
                            <!--<label class="checkbox-inline" v-for="val in item.sku_option_array">
                             <input type="checkbox" :value="val.standardTagName" v-model="item.type_tag">{{val.standardTagName}}
                           </label>-->
                            <el-checkbox-group style="display: inline-block;" v-model="item.type_tag">
                                <el-checkbox :label="val.standardTagName"
                                             v-for="val in item.sku_option_array"></el-checkbox>
                            </el-checkbox-group>
                            <button class="btn btn-default btn-sm" style="margin-left: 15px;"
                                    @click.prevent="delOption(index)">删除
                            </button>
                        </div>
                    </div>
                    <!-- <button class="btn btn-primary" @click.prevent="generate">点击此处生成商品规格表</button> -->
                    <div class="box-body no-padding" style="clear: both;padding-top: 15px;">
                    <label style="font-size: 18px;">商品规格</label>
                    <table class="table table-striped">
                        <thead>
                        <tr>
                            <th>缩略图</th>
                            <th v-for="item in option_array">{{item.sku_option_name}}</th>
                            <th>价格</th>
                            <th>库存</th>
                        </tr>
                        </thead>
                        <tbody class="spec-table">

                        <tr v-for="(item,index) in form.standardInfoIdPojos">
                            <td style="width: 100px;">
                                    <we-ui-uploads :images="item.icon"
                                   :maxCount="1"
                                   :maxSize="1024*1024"
                                   @uploading="uploading"></we-ui-uploads>   
                      
                                   
                                
                            </td>
                            <td v-for="val in item.sku_options">
                                {{val}}
                            </td>
                            <td>
                                <el-input style="width: 100px;" type="text" v-model="item.price" @blur="checkNum(item)" :maxlength="8"></el-input>
                            </td>
                            <td>
                                <el-input style="width: 100px;" type="text" v-model="item.stock" @blur="checkNum2(item)"></el-input>
                            </td>
                            <!-- <td>
                                <el-button
                                size="small"
                                type="danger"
                                @click.native.prevent="deleteRow(index, form.standardInfoIdPojos)">删除</el-button>
                            </td> -->
                            <!--<td><input type="text" v-model="item.sku_stock"></td>-->
                        </tr>

                        </tbody>
                    </table>
                </div>
                    <!-- /.table -->
                    <el-form-item label="总库存：">
                        <span>{{ countAll() }}</span>
                    </el-form-item>
                    <el-form-item label="是否启用库存：">
                        <el-radio class="radio" label="1" v-model="form.stockState" style="margin: 0">启用</el-radio>
                        <el-radio class="radio" label="2" v-model="form.stockState">不启用</el-radio>
                    </el-form-item>
                    <el-form-item label="是否包邮：">
                            <el-radio class="radio" label="1" v-model="form.freightState" style="margin: 0">包邮</el-radio>
                            <el-radio class="radio" label="2" v-model="form.freightState">不包邮</el-radio>
                    </el-form-item>
                    <el-form-item label="运费模板："  v-if="form.freightState==2">
                        <el-select v-model="form.freightId" style="width: 200px;">
                            <el-option :label="item.freightName" :value="item.freightId+''"
                                       v-for="item in carriageList"></el-option>
                        </el-select>
                        <button class="btn btn-primary"@click.prevent="addSize2()">前往新增运费模板</button>
                    </el-form-item>
                    
                </el-form>
                <div>
                <el-form label-width="150px" class="demo-ruleForm" style="width: 90%;" :model="form"  label-position='left'>
                        <el-form-item label="商品略缩图：">
                            <we-ui-uploads :images="form.icon"
                                           :maxCount="1"
                                           :maxSize="1024*1024"
                                           @uploading="uploading"></we-ui-uploads>
                            （尺寸:1:1,340*340）
                        </el-form-item>
                        <el-form-item label="商品轮播图：">
                            <we-ui-uploads :images="form.image"
                                           :maxCount="5"
                                           :maxSize="1024*1024"
                                           :isSort="true"
                                           @uploading="uploading"></we-ui-uploads>
                            （尺寸:1:1,750*750,最多5张）
                        </el-form-item>
                        <el-form-item label="商品详情：">
                            <we-ui-uploads :images="form.details"
                                           :maxCount="150"
                                           :maxSize="1024*1024"
                                           :isSort="true"
                                           @uploading="uploading"></we-ui-uploads>
                            （最多150张）
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" :loading="loading" @click="submitForm()">提交</el-button>
                        </el-form-item>
                    </el-form> 
                </div>
            </div>
           </div>

    </div>

</template>
<style>
    .type {
        display: inline-block;
        width: 30%;
    }
</style>

<script>
    export default {
        data() {
           
            return {
                loading: false,
                form: {
                    classifyCode: '',
                    secondCode: '',
                    thcondCode:'',
                    goodsName: '',
                    price: '',
                    ratio: '',
                    supplierId: '',
                    weight: '',
                    freightId: '',
                    icon: [],
                    image: [],
                    standardId: [],
                    standardTagIdPojos: [],
                    details:[],
                    standardInfoIdPojos: [],
                    state:2,
                    stock:'',
                    fatherCode:2,
                    disPrice:'',
                    freightState:'1',
                    stockState:'2'
                },
                sortList: [],
                secondList: [],
                thirdList:[],
                supplierList: [],
                carriageList: [],
                proportion: [{text: '50%', value: '50'}, {text: '75%', value: '75'}, {
                    text: '100%',
                    value: '100'
                }, {text: '125%', value: '125'}, {text: '150%', value: '150'}, {
                    text: '175%',
                    value: '175'
                }, {text: '200%', value: '200'}, {text: '225%', value: '225'}, {text: '250%', value: '250'}],
                sku_spec_array: [],
                sku_spec:'',
                option_array: [],
                type_tag: '1',
                show: false,
                flag:false,
                URL:URL,
                calendarList:[],
                price1:'',
                price2:'',
                dialogVisible:false,
                info:{
                 data:'',
                 date:''
                },
                changedDay:[],
                showSort:false
            }
        },
        created(){
            this.fetchFreight()
            this.fetchStandard()
            this.fetchData()
            this.fetchList()
        },
        methods: {
            fetchData(){
                 if (sessionStorage.getItem('supplierId')=='UNGYHJ15157486879690000000003') {
                    this.showSort=true
                }else{
                    this.showSort=false
                }
                if (this.$route.params.id==0) {
                    if (sessionStorage.getItem('addpre')) {
                        this.form=JSON.parse(sessionStorage.getItem('addpre'))
                        this.option_array=JSON.parse(sessionStorage.getItem('addpre_s'))
                    }
                    return;
                }
                this.dataApi.ajax('MallGoodListControl/selectGoodsinfo', {goodslistId: this.$route.params.id}, res => {
                    if (res.responseType === 0) {
                        this.form = res.mallGoodsListPojo
                        this.form.icon = [this.URL+res.mallGoodsListPojo.icon]
                        this.form.image=res.mallGoodsListPojo.image
                        for (var i = this.form.image.length - 1; i >= 0; i--) {
                            this.form.image[i]=this.URL+this.form.image[i]
                        }
                        this.sku_option_array = []

                        for (var y in this.form.standardTagIdPojos) {
                            this.sku_option_array[y] = []
                            for (var k in this.form.standardTagIdPojos[y]) {
                                this.sku_option_array[y][k] = {
                                    standardTagName: this.form.standardTagIdPojos[y][k]
                                }
                            }
                           
                        }
                        for (var i = this.form.standardInfoIdPojos.length - 1; i >= 0; i--) {
                            if (this.form.standardInfoIdPojos[i].icon) {
                                this.form.standardInfoIdPojos[i].icon=[URL+this.form.standardInfoIdPojos[i].icon]
                            }else  this.form.standardInfoIdPojos[i].icon=[]
                            
                        }
                        for (var x in this.form.standardId) {
                            this.option_array.push({
                                sku_option_name: this.form.standardId[x],
                                sku_option_array: this.sku_option_array[x],
                                type_tag: this.form.standardTagIdPojos[x]
                            })
                        }
                        if (res.mallGoodsListPojo.details=='') {
                            this.form.details=[]
                        }else{
                            var arr=[]
                            arr=res.mallGoodsListPojo.details.split(',')
                            for (var i = arr.length - 1; i >= 0; i--) {
                                arr[i]=this.URL+arr[i]
                            }
                            this.form.details=arr
                        }
                    }
                });
            },
            submitForm(){
                  if (this.showSort&&this.form.thcondCode=='') {
                      this.$message({
                            type: 'warning',
                            message: '请选择分类!'
                     });
                    return false;
                 }
                 if (!this.form.goodsName) {
                    this.$message({
                            type: 'warning',
                            message: '请填写商品名称!'
                     });
                    return false;
                }
                 if (!this.form.price || !isFloat(this.form.price)) {
                    this.$message({
                            type: 'warning',
                            message: '商品原价不正确!'
                     });
                    return false;
                }
                if (!this.form.disPrice || !isFloat(this.form.disPrice)) {
                    this.$message({
                            type: 'warning',
                            message: '商品现价不正确!'
                     });
                    return false;
                }
                if (parseInt(this.form.disPrice)>parseInt(this.form.price)){
                    this.$message({
                            type: 'warning',
                            message: '商品现价不能大于原价!'
                     });
                    return false;
                }
                 if (!this.form.weight || !isFloat(this.form.weight)) {
                    this.$message({
                            type: 'warning',
                            message: '商品重量不正确!'
                     });
                    return false;
                }
                if (!this.form.ratio) {
                    this.$message({
                            type: 'warning',
                            message: '请选择奖励比例!'
                     });
                    return false;
                }
               
                  for (var i = this.option_array.length - 1; i >= 0; i--) {
                      if(this.option_array[i].type_tag==0){
                         this.$message({
                                type: 'warning',
                                message: '请选择规格!'
                          });
                         return
                      }

                  }
                  for (var i = this.form.standardInfoIdPojos.length - 1; i >= 0; i--) {
                      if(this.form.standardInfoIdPojos[i].icon.length==0){
                         this.$message({
                                type: 'warning',
                                message: '请上传规格缩略图!'
                          });
                         return
                      }

                  }
                  if (this.option_array.length==0) {
                    this.$message({
                                type: 'warning',
                                message: '请至少选择一种规格!'
                    });
                    return
                  }
                  if (this.form.freightState=='2'&&!this.form.freightId) {
                    this.$message({
                            type: 'warning',
                            message: '请选择运费模板!'
                     });
                    return false;
                }
                if (this.form.icon.length==0) {
                    this.$message({
                            type: 'warning',
                            message: '请上传商品略缩图!'
                     });
                    return false;
                }
                if (this.form.image.length==0) {
                    this.$message({
                            type: 'warning',
                            message: '请上传商品轮播图!'
                     });
                    return false;
                }
                if (this.form.details.length==0) {
                    this.$message({
                            type: 'warning',
                            message: '请上传商品详情!'
                     });
                    return false;
                }
                this.form.standardId = []
                this.form.standardTagIdPojos = []
                for (var i in this.option_array) {
                    this.form.standardId.push(this.option_array[i].sku_option_name);
                }
                for (var key in this.option_array) {
                    this.form.standardTagIdPojos.push(this.option_array[key].type_tag)
                }
                if (this.form.standardInfoIdPojos.length <= 0) {
                     this.$message({
                            type: 'warning',
                            message: '请填写商品规格!'
                     });
                    return false;
                }
                //log(this.info.spec_array)
               for (var i = this.form.standardInfoIdPojos.length - 1; i >= 0; i--) {
                      if(this.form.standardInfoIdPojos[i].price==0){
                         this.$message({
                                type: 'warning',
                                message: '商品规格价格不能为0!'
                          });
                         return
                      }

                  }

                if (this.form.price.toString().indexOf('.') > 0 && this.form.price.split('.')[1].length > 2) {
                    this.showMsg("价格只能精确到小数点后两位!","warning")
                    return;
                }
                sessionStorage.setItem('data',JSON.stringify(this.form))
                var data=JSON.parse(sessionStorage.getItem('data'))
                data.standardId = JSON.stringify(data.standardId)
                data.standardTagIdPojos = JSON.stringify(data.standardTagIdPojos)
                for (var i = data.standardInfoIdPojos.length - 1; i >= 0; i--) {
                    var icon=new String(data.standardInfoIdPojos[i].icon)
                    data.standardInfoIdPojos[i].icon=icon.replace(this.URL,'')
                }
                
                data.standardInfoIdPojos = JSON.stringify(data.standardInfoIdPojos)
                var icon = new String(data.icon)
                data.icon=icon.replace(this.URL,'')
                for (var i = data.image.length - 1; i >= 0; i--) {
                    data.image[i]=data.image[i].replace(this.URL,'')
                }
                data.image = JSON.stringify(data.image)
                for (var i = data.details.length - 1; i >= 0; i--) {
                    data.details[i]=data.details[i].replace(this.URL,'')
                }
                data.details=data.details.join(',')
                if (data.freightState=='1') {
                    data.freightId='MF15058760840430000000170'
                }
                data.stock=this.countAll()

                this.loading=true
                if (this.$route.params.id==0) {
                    this.dataApi.ajax('MallGoodListControl/addGoodsList', data, res => {
                    if (res.responseType === 0) {
                        this.$message({
                            type: 'success',
                            message: '新增成功!'
                        });
                        this.loading=false

                        history.back(-1)
                        
                    }
                  });
                }else{
                    this.dataApi.ajax('MallGoodListControl/editGoodsList', data, res => {
                    if (res.responseType === 0) {
                        this.$message({
                            type: 'success',
                            message: '编辑成功!'
                        });
                         this.loading=false
                       history.back(-1)
                    }
                  }); 
                }
                sessionStorage.removeItem('data')
                
            },
            fanhui(){
                history.back(-1)
            },
            fetchFreight(){
                this.dataApi.ajax('FreightControl/queryFreightByAll', null, res => {
                    if (res.responseType === 0) {
                        this.carriageList = res.freightPojos
                    }
                });
            },
            fetchStandard(){
                this.dataApi.ajax('StandardControl/selectStandardList', null, res => {
                    if (res.responseType === 0) {
                        this.sku_spec_array = res.standardPojos
                    }
                });
            },
            delOption(index) {
                this.option_array.splice(index, 1)
                this.generate()
            },
            generate() {
                var option_array = this.option_array;
                var spec_array = this.form.standardInfoIdPojos = [];
                if (option_array.length <= 0)
                    return false;

                var select = [];
                for (var i in option_array) {
                    if (option_array[i].type_tag.length > 0) {
                        select.push(option_array[i].type_tag);
                    } else {
                        return false;
                    }

                }

                var ret = this.doExchange(select)
                for (var i = 0; i < ret.length; i++) {
                    var proObj = {};
                    var retArr = ret[i].split('|');
                    proObj['sku_options'] = [];
                    for (var y = 0; y < retArr.length; y++) {

                        proObj['sku_options'].push(retArr[y])

                    }
                    
                    proObj['icon'] = [];
                    proObj['price'] = 0;
                    proObj['stock'] = 0;

                    spec_array.push(proObj);
                }

            },
            doExchange(doubleArrays) {

                var len = doubleArrays.length;

                if (len >= 2) {
                    var len1 = doubleArrays[0].length;
                    var len2 = doubleArrays[1].length;
                    var newLen = len1 * len2;
                    var temp = new Array(newLen);
                    var index = 0;

                    for (var i = 0; i < len1; i++) {
                        for (var j = 0; j < len2; j++) {
                            temp[index] = doubleArrays[0][i] + '|' + doubleArrays[1][j];
                            index++;
                        }
                    }

                    var newArray = new Array(len - 1);
                    for (var i = 2; i < len; i++) {
                        newArray[i - 1] = doubleArrays[i];
                    }
                    newArray[0] = temp;
                    return this.doExchange(newArray);

                } else {
                    return doubleArrays[0];
                }
            },
            select(){
                if (!this.sku_spec.standardId) {
                    return false;
                }

                var arr = this.option_array;
                for (var i in arr) {
                    if (arr[i].sku_option_name === this.sku_spec.standardName) {
                        this.sku_spec=''
                        return false;
                    }
                }
                if (arr.length >= 5) {
                    return false;
                }
                this.dataApi.ajax('StandardControl/selectStandTagList', {standardId: this.sku_spec.standardId}, res => {
                    //console.log(res.standardTagPojos)
                    if (res.responseType === 0) {
                        this.option_array.push({
                            sku_option_name: this.sku_spec.standardName,
                            sku_option_array: res.standardTagPojos,
                            type_tag: [],
                        })
                        this.generate()
                    }
                });

            },
            uploading(f) {
                this.dataApi.upload('file/upload', f.file, res => {
                    //console.log(res)
                    if (res.responseType === 0) {
                        f.images.splice(f.index,1,this.URL+res.fileName)
                    }
                });
                
            },
            addSize(){
                sessionStorage.setItem('back','1')
                sessionStorage.setItem('addpre',JSON.stringify(this.form))
                sessionStorage.setItem('addpre_s',JSON.stringify(this.option_array))
                this.$router.push('/mall/size_list')
            },
            addSize2(){
                sessionStorage.setItem('back','1')
                sessionStorage.setItem('addpre',JSON.stringify(this.form))
                sessionStorage.setItem('addpre_s',JSON.stringify(this.option_array))
                this.$router.push('/mall/freight_list')
            },
            deleteRow(index, rows) {
                rows.splice(index, 1);
            },
            countAll(){
                var all=0
                for (var i = this.form.standardInfoIdPojos.length - 1; i >= 0; i--) {
                  all=all+parseInt(this.form.standardInfoIdPojos[i].stock)

                }
                return all;
            },
             checkNum(item){
                if (!isFloat(item.price)) {
                   this.showMsg('价格只能输入正数','warning')
                   item.price=0
                }else{
                     item.price=parseFloat(Math.abs(item.price))
                }
                
            },
            checkNum2(item){
                if (!isNumber(item.stock)) {
                   this.showMsg('库存只能输入正整数','warning')
                   item.stock=0
                }else{
                     item.stock=parseFloat(Math.abs(item.stock))
                }
            },
            fetchList(){
                this.dataApi.ajax('MallGoodClassifyControl/selectOneList', { location:1}, res => {
                    if (res.responseType === 0) {
                        this.sortList = res.goodsClassifyPojos
                    }
                });
            },
             selectSort(){
                if (this.flag === true) this.form.secondCode = ''
                this.flag = true;
                this.dataApi.ajax('MallGoodClassifyControl/selectListOne', {location:1,classifyName: this.form.classifyCode}, res => {
                    //console.log(res)
                    if (res.responseType === 0) {
                        this.secondList = res.goodsClassifyPojos
                    }
                });

            },
            selectSort2(){
                if (this.flag2 === true) this.form.thcondCode = ''
                this.flag2 = true;
                this.dataApi.ajax('MallGoodClassifyControl/selectListOne', {location:1,classifyName: this.form.secondCode}, res => {
                    //console.log(res)
                    if (res.responseType === 0) {
                        this.thirdList = res.goodsClassifyPojos
                    }
                });

            },
        }
    }
</script>
